package main
import(
	"fmt"
	"math/rand"
	"sort"
)

//1.声明结构体
type Hero struct{
	Name string
	Age int
}

//2.声明Hero 结构体切片类型
type HeroSlice []Hero

//3.实现interface 接口
func (hs HeroSlice) Len() int{
	return len(hs)
}

//4.Less方法决定用什么标准排序
func (hs HeroSlice) Less(i,j int) bool{
	return hs[i].Age > hs[j].Age
}

//4.swap方法交换
func (hs HeroSlice) Swap(i,j int) {
	temp := hs[i]
	hs[i] = hs[j]
	hs[j] = temp
	////等价上面3句
	//hs[i],hs[j] = hs[j],hs[i]
}

func main(){
	//测试
	var Heroes HeroSlice
	for i :=0 ;i < 10 ; i++ {
		hero := Hero{
			Name: fmt.Sprintf("英雄~%d",rand.Intn(100)),
			Age:rand.Intn(100),
		}
		Heroes = append(Heroes , hero)
	}

	//看排序前的顺序
	for _,v := range Heroes{
		fmt.Println(v)
	}

	//看排序后的顺序
	fmt.Println("排序后的顺序")
	sort.Sort(Heroes)
	for _,v := range Heroes{
		fmt.Println(v)
	}

}
